package pri.orm.Service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import pri.orm.entity.User;
import pri.orm.repository.DepartmentDao;
import pri.orm.repository.UserDao;
import pri.orm.entity.Department;

import javax.annotation.Resource;
import java.util.UUID;

@Service
public class UserService implements IUserService{

    @Resource
    private UserDao userDao;
    @Resource
    private DepartmentDao departmentDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int newUser(String userName) {

        User user = new User();
        user.setName(userName);

        Department department = new Department();
        department.setName(UUID.randomUUID().toString());
        department.setOrderNo(1);
        department.setLevels(1);

        userDao.save(user);
        System.out.println(userDao.existsById(user.getId())+"[id]"+user.getId());
        int i = 1/0;
        departmentDao.save(department);

        return 1;
    }

    @Transactional
    @Override
    public int newUser2(String userName) {
        try{
            User user = new User();
            user.setName(userName);

            Department department = new Department();
            department.setName(UUID.randomUUID().toString());
            department.setOrderNo(1);
            department.setLevels(1);

            userDao.save(user);
            System.out.println(userDao.existsById(user.getId())+"[id]"+user.getId());
            int i = 1/0;
            departmentDao.save(department);

            return 1;
        }catch (ArithmeticException ex){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }

    }
}
